using VOL.demo.IRepositories;
using VOL.demo.IServices;
using VOL.Core.BaseProvider;
using VOL.Entity.DomainModels;
using VOL.Core.Utilities;
using System.Linq;
using VOL.Core.Extensions;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using VOL.Core.Extensions.AutofacManager;

namespace VOL.demo.Services
{
    public partial class GoodsBatchModelService
    {
        // 获取Repository的实例
        private IGoodsBatchModelRepository _batchRepository => AutofacContainerModule.GetService<IGoodsBatchModelRepository>();
        private IInventoryModelRepository _inventoryRepository => AutofacContainerModule.GetService<IInventoryModelRepository>();
        private IproductinformationmodelRepository _goodsRepository => AutofacContainerModule.GetService<IproductinformationmodelRepository>();
        private IwarehousemodelRepository _warehouseRepository => AutofacContainerModule.GetService<IwarehousemodelRepository>();
        
        /// <summary>
        /// 根据货品ID和仓库ID获取批次信息
        /// </summary>
        /// <param name="goodsId">货品ID</param>
        /// <param name="warehouseId">仓库ID</param>
        /// <returns></returns>
        public List<GoodsBatchModel> GetBatchesByGoodsAndWarehouse(long goodsId, long warehouseId)
        {
            return _batchRepository.Find(x => x.GoodsId == goodsId && x.WarehouseId == warehouseId && x.IsDel == 0);
        }

        /// <summary>
        /// 批量保存批次信息
        /// </summary>
        /// <param name="batches">批次列表</param>
        /// <returns></returns>
        public WebResponseContent SaveBatches(List<GoodsBatchModel> batches)
        {
            return _batchRepository.DbContextBeginTransaction(() =>
            {
                try
                {
                    foreach (var batch in batches)
                    {
                        batch.SetCreateDefaultVal();
                    }
                    _batchRepository.AddRange(batches, true);
                    return new WebResponseContent().OK("批次信息保存成功");
                }
                catch (Exception ex)
                {
                    return new WebResponseContent().Error($"批次信息保存失败：{ex.Message}");
                }
            });
        }

        /// <summary>
        /// 计算期初库存总量
        /// </summary>
        /// <param name="batches">批次列表</param>
        /// <returns></returns>
        public int CalculateTotalQuantity(List<GoodsBatchModel> batches)
        {
            return batches?.Sum(x => x.Quantity) ?? 0;
        }

        /// <summary>
        /// 获取货品批次与库存联查列表（分页）
        /// </summary>
        public async Task<(List<GoodsBatchInventoryDto> Data, int TotalCount)> GetBatchInventoryPagedListAsync(
            int pageIndex = 1, 
            int pageSize = 20, 
            long? goodsId = null, 
            long? warehouseId = null, 
            string batchNo = null, 
            string keyword = null)
        {
            return await Task.Run(() =>
            {
                try
                {
                    // 获取批次数据
                    var batchQuery = _batchRepository.Find(x => x.IsDel == 0).AsQueryable();

                    // 应用批次筛选条件
                    if (goodsId.HasValue)
                    {
                        batchQuery = batchQuery.Where(x => x.GoodsId == goodsId.Value);
                    }

                    if (warehouseId.HasValue)
                    {
                        batchQuery = batchQuery.Where(x => x.WarehouseId == warehouseId.Value);
                    }

                    if (!string.IsNullOrEmpty(batchNo))
                    {
                        batchQuery = batchQuery.Where(x => x.BatchNo.Contains(batchNo));
                    }

                    var batches = batchQuery.ToList();

                    // 获取库存数据
                    var inventories = _inventoryRepository.Find(x => x.IsDel == 0).ToList();

                    // 获取货品数据
                    var goods = _goodsRepository.Find(x => x.IsDel == null || x.IsDel == 0).ToList();

                    // 获取仓库数据
                    var warehouses = _warehouseRepository.Find(x => x.IsDel == null || x.IsDel == 0).ToList();

                    // 在内存中进行联表查询
                    var query = from batch in batches
                                join inventory in inventories
                                    on new { batch.GoodsId, batch.WarehouseId, batch.BatchNo }
                                    equals new { inventory.GoodsId, inventory.WarehouseId, inventory.BatchNo }
                                    into inventoryGroup
                                from inv in inventoryGroup.DefaultIfEmpty()
                                join good in goods
                                    on batch.GoodsId equals good.Id
                                    into goodsGroup
                                from gd in goodsGroup.DefaultIfEmpty()
                                join warehouse in warehouses
                                    on batch.WarehouseId equals warehouse.Id
                                    into warehouseGroup
                                from wh in warehouseGroup.DefaultIfEmpty()
                                where gd != null && wh != null
                                select new
                                {
                                    Batch = batch,
                                    Inventory = inv,
                                    Goods = gd,
                                    Warehouse = wh
                                };

                    // 应用关键词筛选
                    if (!string.IsNullOrEmpty(keyword))
                    {
                        query = query.Where(x =>
                            (x.Goods.goodsCode != null && x.Goods.goodsCode.Contains(keyword)) ||
                            (x.Goods.goodsName != null && x.Goods.goodsName.Contains(keyword)) ||
                            (x.Warehouse.WarehouseCode != null && x.Warehouse.WarehouseCode.Contains(keyword)) ||
                            (x.Warehouse.WarehouseName != null && x.Warehouse.WarehouseName.Contains(keyword)) ||
                            (x.Batch.BatchNo != null && x.Batch.BatchNo.Contains(keyword)));
                    }

                    // 获取总数
                    var totalCount = query.Count();

                    // 分页查询
                    var dataList = query
                        .OrderByDescending(x => x.Batch.CreateDate)
                        .Skip((pageIndex - 1) * pageSize)
                        .Take(pageSize)
                        .ToList();

                    // 映射到DTO
                    var now = DateTime.Now;
                    var result = dataList.Select(x => new GoodsBatchInventoryDto
                    {
                        BatchId = x.Batch.Id,
                        BatchNo = x.Batch.BatchNo,
                        GoodsId = x.Batch.GoodsId,
                        GoodsCode = x.Goods.goodsCode,
                        GoodsName = x.Goods.goodsName,
                        WarehouseId = x.Batch.WarehouseId,
                        WarehouseCode = x.Warehouse.WarehouseCode,
                        WarehouseName = x.Warehouse.WarehouseName,
                        BatchQuantity = x.Batch.Quantity,
                        CurrentQty = x.Inventory?.CurrentQty,
                        ProductionDate = x.Batch.ProductionDate,
                        BatchExpireDate = x.Batch.ExpireDate,
                        InventoryExpireDate = x.Inventory?.ExpireDate,
                        UpperLimit = x.Inventory?.UpperLimit,
                        LowerLimit = x.Inventory?.LowerLimit,
                        BatchRemark = x.Batch.Remark,
                        InventoryRemark = x.Inventory?.Remark,
                        CreateDate = x.Batch.CreateDate,
                        Creator = x.Batch.Creator,
                        // 计算预警状态
                        IsExpiringSoon = x.Batch.ExpireDate.HasValue &&
                                        x.Batch.ExpireDate.Value <= now.AddDays(30),
                        IsBelowLowerLimit = x.Inventory != null &&
                                           x.Inventory.LowerLimit.HasValue &&
                                           x.Inventory.CurrentQty < x.Inventory.LowerLimit.Value,
                        IsAboveUpperLimit = x.Inventory != null &&
                                           x.Inventory.UpperLimit.HasValue &&
                                           x.Inventory.CurrentQty > x.Inventory.UpperLimit.Value,
                        // 数据状态
                        DataStatus = x.Inventory == null ? "仅有批次数据" :
                                    x.Batch.Quantity != x.Inventory.CurrentQty ? "数据不一致" : "正常"
                    }).ToList();

                    return (result, totalCount);
                }
                catch (Exception ex)
                {
                    throw new Exception($"获取货品批次库存联查列表失败：{ex.Message}");
                }
            });
        }
    }
}
